

<h1>Welcome to <i><?php echo CHtml::encode(Yii::app()->name); ?></i></h1>
	<div class="col_1_2">
		<div class="not-found" id="notfound"></div>
		<div class="">
			<input type="text" id="fullAddress" placeholder="Enter your address"> 
			<input type="button" id="btnCheckAddress" value="Check Address" onclick="geocode()"/>
		</div>
		<div id="map_div">
			<div class="maps" id="Maps" style="display: none;"></div>
			<div class="address" id="address"></div>
		</div>
	</div>
	<?php
	if($flag)
		echo '<p>You posted</p>';
	?>
	<div class="col_1_2" id="eventDetail" style="display:<?php if(isset($_POST['Post']) && $flag == false) echo 'block'; else echo 'none';?>">
		<?php
		$form = $this->beginWidget('CActiveForm', array(
			'id'=>'contact-form',
			'enableClientValidation'=>true,
			'clientOptions'=>array(
				'validateOnSubmit'=>true,
			),
		));?>
			<?php echo $form->hiddenField($post, 'street', array('id' => 'street'));?>
			<?php echo $form->hiddenField($post, 'city', array('id' => 'city'));?>
			<?php echo $form->hiddenField($post, 'state', array('id' => 'state'));?>
			<?php echo $form->hiddenField($post, 'zip', array('id' => 'zip'));?>
			<?php echo $form->hiddenField($post, 'lat', array('id' => 'lat'));?>
			<?php echo $form->hiddenField($post, 'lng', array('id' => 'lng'));?>
			
			<div class="row">
				<label>Title</label>
				<div class="">
					<?php echo $form->textField($post, 'title', array("placeholder" => "Enter your title"));?>
					<?php echo $form->Error($post, 'title')?>
				</div>
			</div>
			<div class="row">
				<label>Description</label>
				<div class="">
					<?php echo $form->textArea($post, 'description', array("placeholder" => "Enter your description", 'col' => '80', 'row' => '3'));?>
					<?php echo $form->Error($post, 'description')?>
				</div>
			</div>
			<div class="row">
				<label>Start date</label>
				<div class="">
					<?php echo $form->textField($post, 'start_date');?>
				</div>
			</div>
			<div class="row">
				<label>End date</label>
				<div class="">
					<?php echo $form->textField($post, 'end_date');?>
				</div>
			</div>
			<div class="row">
				<label>Time</label>
				<div class="">
					<?php echo $form->textField($post, 'timer', array("placeholder" => "Enter your time"));?>
				</div>
			</div>
			<div class="row">
				<label>Your name</label>
				<div class="">
					<?php echo $form->textField($post, 'your_name', array("placeholder" => "Enter your name"));?>
				</div>
			</div>
			<div class="row">
				<label>Email</label>
				<div class="">
					<?php echo $form->textField($post, 'email', array("placeholder" => "Enter your email"));?>
				</div>
			</div>
			<div class="row">
				<label>Password</label>
				<div class="">
					<?php echo $form->textField($post, 'password', array("placeholder" => "Enter your password"));?>
				</div>
			</div>
			<div class="row">
				<input type="submit" value="Submit">
			</div>
		<?php $this->endWidget();?>
	</div>
	<div id="map-canvas">
	</div>
	<div class="cloneList"></div>
	<div class="event-list">
		<?php
			if(count($model) >0):
				$data = array();
				$avgLat = 0;
				$avgLng = 0;
				$i=0;
				$arrLat = array();
				$arrLng = array();
				foreach ($model as $key => $value):?>
					<div id="<?php echo $value['id']?>">
						<h3><?php echo $value['title']?>
					</div>
				<?php 
					$i++;
					$m = [$value['lat'], $value['lng'], "0", $value['id']];
					$avgLat += $value['lat'];
					$avgLng += $value['lng'];
					array_push($data,$m);
					array_push($arrLat, $value['lat']);
					array_push($arrLng, $value['lng']);				
				endforeach;
				$latMin = min($arrLat);
				$latMax = max($arrLat);
				$lngMin = min($arrLng);
				$lngMax = max($arrLng);
				//echo "<pre>";print_r($data);
		?>
		<script type="text/javascript">
			var moved = false;
		    function initialize() { 
		    	var data = <?php echo json_encode($data);?>
				
			    //var myLatlngOLD = new google.maps.LatLng(32.931924, -105.970305);
		    	var myLatlng = new google.maps.LatLng(<?php echo $avgLat/$i?>, <?php echo $avgLng/$i?>);

		    	//this uses the range of the points as the bounds
			    var myLatlngBounds = new google.maps.LatLngBounds(
			            new google.maps.LatLng(<?php echo $latMin?>, <?php echo $lngMin?>)
			            , new google.maps.LatLng(<?php echo $latMax?>, <?php echo $lngMax?>)
			        );
			    //this uses the radius of the query as the bounds
			    // var myLatlngBoundsOLD = new google.maps.LatLngBounds(
			    //         new google.maps.LatLng(32.75925003051758, -106.12705840499329)
			    //         , new google.maps.LatLng(33.03925003051758, -105.79358063309265)
			    //     );

		        var mapOptions = {
		        	scaleControl: true,
		            center: myLatlng,
		            zoom: 10,
		            mapTypeId: google.maps.MapTypeId.ROADMAP
		        };
		        
		        var map = new google.maps.Map(document.getElementById("map-canvas"),
		                        mapOptions);
		        map.fitBounds(myLatlngBounds);

			    var dots = [
		        	"http://6a66e047f3e460001b08-9c8de170feb0883ba5649f745b33cd82.r86.cf2.rackcdn.com/ico_yardsale@2x.png",
		         	//"http://silverlandhotels.com/themes/default/frontend/<?php echo Yii::app()->theme->baseUrl?>/frontend/images/star.png",
		        	"http://6a66e047f3e460001b08-9c8de170feb0883ba5649f745b33cd82.r86.cf2.rackcdn.com/ico_featured@2x.png"];
		        for(var i=0;i<data.length;i++){
			        var row = data[i];
			        var image = dots[row[2]];
			        var myLatlng = new google.maps.LatLng(row[0],row[1]);
			        var marker = new google.maps.Marker({
			            position: myLatlng, 
			            map: map,
			            animation: google.maps.Animation.DROP,
			            icon: image,
			            title: "",
			            html: row[3]
			        });   
			        infoWnd = new google.maps.InfoWindow();
			        var content = 'content';
			        var marker = createMarker(map, myLatlng, content);

			        var infowindow = new google.maps.InfoWindow({ content: content, maxWidth: 500});
		        	// google.maps.event.addListener(marker, 'click', function() {
			        //     //map.panTo(this.getPosition());
			        //     //infowindow.open(map,marker);
			        //     infowindow.setContent("<strong>" + content + "</title>");
			        //     infowindow.open(map, marker);
			        //     map.panTo(marker.getPosition());

			        //     var clone = $("#"+this.html).clone();			            
			        //         this.setIcon("http://6a66e047f3e460001b08-9c8de170feb0883ba5649f745b33cd82.r86.cf2.rackcdn.com/ico_selected@2x.png");
			        //         var image = $(clone).find(".markerIcon");
			        //         $(image).attr("src","http://6a66e047f3e460001b08-9c8de170feb0883ba5649f745b33cd82.r86.cf2.rackcdn.com/ico_selected@2x.png");
			        //         if(!moved){
			        //             $("html, body").animate({"scrollTop":"340px"}, 750);
			        //             moved = true;
			        //         }
			                
			        //     $(clone).addClass("clone").hide();
			        //     $("#"+this.html).remove();
			        //     $('.cloneList').prepend(clone);
			        //     $(clone).slideDown();
			        // });
		        }
		        //box coords sét theo bán kính miles
		        var boxCoords = [
		            new google.maps.LatLng(<?php echo $latMin?>, <?php echo $lngMin?>),
		            new google.maps.LatLng(<?php echo $latMax?>, <?php echo $lngMin?>),
		            new google.maps.LatLng(<?php echo $latMax?>, <?php echo $lngMax?>),
		            new google.maps.LatLng(<?php echo $latMin?>, <?php echo $lngMax?>)
		        ];
		        // Construct the polygon
		         // Note that we don't specify an array or arrays, but instead just
		         // a simple array of LatLngs in the paths property
		        var box = new google.maps.Polygon({
		            paths: boxCoords,
		            strokeColor: "0000FF",
		            strokeOpacity: 0.2,
		            strokeWeight: 10,
		            fillColor: "#FF0000",
		            fillOpacity: 0 
		        });

		        box.setMap(map);
		    }

		    google.maps.event.addDomListener(window, 'load', initialize);
		</script>
		<?php endif;?>
	</div>
<style>
.container .col_1_2{width: 45%;float:left;padding:10px;}
.maps{
	width: 100%;
	height: 300px;
}
#map-canvas{
	width: 100%;
	height: 300px;
}
</style>
<script type="text/javascript">
	
var moved = false; 
function initialize() {
	var data = [
				['-105.94595', '32.901466', '1', "169360773"], 
				['-105.94337', '32.899937', '0', "98754009"], 
				['-105.99724', '32.88457', '0', "162763451"], 
				['-105.93219', '32.91826', '0', "167744027"], 
				['-105.94165', '32.889343', '0', "169360690"], 
				['-105.955734', '32.879696', '0', "169443189"]
			];
			
	var myLatlngOLD = new google.maps.LatLng(32.898978, -105.96471500000001);
	var myLatlng = new google.maps.LatLng(32.89925003051758, -105.96031951904297);

	//this uses the range of the points as the bounds
	var myLatlngBounds = new google.maps.LatLngBounds(
			new google.maps.LatLng(32.879696, -105.99724)
			, new google.maps.LatLng(32.91826, -105.93219)
		);
	//this uses the radius of the query as the bounds
	var myLatlngBoundsOLD = new google.maps.LatLngBounds(
			new google.maps.LatLng(32.75925003051758, -106.12705840499329)
			, new google.maps.LatLng(33.03925003051758, -105.79358063309265)
		);
	//0=normal, 1=featured
	
		var dots = ["http://6a66e047f3e460001b08-9c8de170feb0883ba5649f745b33cd82.r86.cf2.rackcdn.com/ico_yardsale@2x.png","http://6a66e047f3e460001b08-9c8de170feb0883ba5649f745b33cd82.r86.cf2.rackcdn.com/ico_featured@2x.png"]
	
	var myOptions = {
      //zoom: 14,
      scaleControl: true,
      center: myLatlng,
      maxZoom: 16,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    map.fitBounds(myLatlngBounds);
    
    for(var i=0;i<data.length;i++){
        var row = data[i];
        var image = dots[row[2]];
        var myLatlng = new google.maps.LatLng(row[1],row[0]);
        var marker = new google.maps.Marker({
            position: myLatlng, 
            map: map,
            /*animation: google.maps.Animation.DROP,*/
            icon: image,
            title: "",
            html: row[3]
        });   

        google.maps.event.addListener(marker, 'click', function() {
        	//map.panTo(this.getPosition());
        	var clone = $("#"+this.html).clone();
        	
    			this.setIcon("http://6a66e047f3e460001b08-9c8de170feb0883ba5649f745b33cd82.r86.cf2.rackcdn.com/ico_selected@2x.png");
    			var image = $(clone).find(".markerIcon");
    			$(image).attr("src","http://6a66e047f3e460001b08-9c8de170feb0883ba5649f745b33cd82.r86.cf2.rackcdn.com/ico_selected@2x.png");
    			if(!moved){
    				$("html, body").animate({"scrollTop":"340px"}, 750);
    				moved = true;
    			}
				
        	$(clone).addClass("clone").hide();
        	$("#"+this.html).remove();
            $("#yssEvents .right .theMap .cloneList").prepend(clone);
            $(clone).slideDown();
        });
    }//for


    	  var boxCoords = [
    	    new google.maps.LatLng(32.75925003051758, -106.12705840499329),
    	    new google.maps.LatLng(33.03925003051758, -106.12705840499329),
    	    new google.maps.LatLng(33.03925003051758, -105.79358063309265),
    	    new google.maps.LatLng(32.75925003051758, -105.79358063309265)
    	  ];

    	  // Construct the polygon
    	  // Note that we don't specify an array or arrays, but instead just
    	  // a simple array of LatLngs in the paths property
    	  var box = new google.maps.Polygon({
    	    paths: boxCoords,
    	    strokeColor: "#0000FF",
    	    strokeOpacity: 0.2,
    	    strokeWeight: 10,
    	    /*fillColor: "#FF0000",*/
    	    fillOpacity: 0 
    	  });

    	  box.setMap(map);
    	    
}//initialize()

$(document).ready(function(){
	var children = $("#yssEvents .eventList").children(".moveToBottom");
	
	if(children.length > 0) $(".mobileListing").show().html("There are " + children.length + " mobile listings shown only on the map.");
	
	for(var i = 0; i < children.length; i++){
		var clone = $(children[i]).clone();
		$(children[i]).remove();
		$("#yssEvents .eventList").append(clone);
	}
	
	children = $("#yssEvents .event .eventdesc")
	for(var i = 0; i < children.length; i++){
		if($(children[i])[0].scrollHeight > 114){
			$(children[i]).append("<span class='readMore' onclick=\"bookoo.yardSaleSearch.toggleMore(this)\">. . . More &raquo;</span>");
		}
	}
});
</script>
<!--click on sidebar-->
<script type="text/javascript">
	
    var map = null;
    var def_latlng = new google.maps.LatLng(-34.397, 150.644);
    var def_zoom = 8;
    var infoWnd = null;

    var stationList = [
        {"latlng": [35.681382, 139.766084], name: "Tokyo Station"},
        {"latlng": [35.630152, 139.74044], name: "Shinagawa Station"},
        {"latlng": [35.507456, 139.617585], name: "Shin-Yokohama Station"},
        {"latlng": [35.25642, 139.154904], name: "Odawara Station"},
        {"latlng": [35.103217, 139.07776], name: "Atami Station"},
        {"latlng": [35.127152, 138.910627], name: "Mishima Station"},
        {"latlng": [35.142015, 138.663382], name: "Shin-Fuji Station"},
        {"latlng": [34.97171, 138.38884], name: "Shizuoka Station"},
        {"latlng": [34.769758, 138.014928], name: "Kakegawa Station"},
        {"latlng": [34.703741, 137.734442], name: "Hamamatsu Station"},
        {"latlng": [34.762811, 137.381651], name: "Toyohashi Station"},
//        {"latlng": [34.96897, 137.060662], name: "Mikawa-Anjyo Station"},
//        {"latlng": [35.170694, 136.881637], name: "Nagoya Station"},
//        {"latlng": [35.315705, 136.685593], name: "Gifu-Hashima Station"},
//        {"latlng": [35.314188, 136.290488], name: "Yonehara Station"},
//        {"latlng": [34.985458, 135.757755], name: "Kyoto Station"},
//        {"latlng": [34.73348, 135.500109], name: "Shin-Osaka Station"}
    ];


    function initialize() {
        var mapOptions = {
            zoom: def_zoom,
            center: def_latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map_canvas'),
                mapOptions);

        //Creates a infowindow object.
        infoWnd = new google.maps.InfoWindow();

        //Mapping markers on the map
        var bounds = new google.maps.LatLngBounds();
        var station, i, latlng;
        for (i in stationList) {
            //Creates a marker
            station = stationList[i];
            latlng = new google.maps.LatLng(station.latlng[0], station.latlng[1]);
            bounds.extend(latlng);
            var marker = createMarker(
                    map, latlng, station.name
                    );

            //Creates a sidebar button for the marker
            createMarkerButton(marker);
        }
        //Fits the map bounds
        map.fitBounds(bounds);
    }


    function createMarker(map, latlng, title) {
        //Creates a marker
        var marker = new google.maps.Marker({
            position: latlng,
            map: map,
            title: title
        });

        //The infoWindow is opened when the sidebar button is clicked
        google.maps.event.addListener(marker, "click", function() {
            infoWnd.setContent("<strong>" + title + "</title>");
            infoWnd.open(map, marker);
            map.panTo(marker.getPosition());
        });
        return marker;
    }


    function createMarkerButton(marker) {
        //Creates a sidebar button
        var ul = document.getElementById("marker_list");
        var li = document.createElement("li");
        var title = marker.getTitle();
        li.innerHTML = '<a>'+title+'</a>';
        ul.appendChild(li);

        //Trigger a click event to marker when the button is clicked.
        google.maps.event.addDomListener(li, "click", function() {
            google.maps.event.trigger(marker, "click");
        });
    }

    window.onload = initialize();

</script>
<?php
/* @var $this SiteController */
/* @var $error array */

$this->pageTitle=Yii::app()->name . ' - Error';
$this->breadcrumbs=array(
	'Error',
);
?>

<h2>Error <?php echo $code; ?></h2>

<div class="error">
<?php echo CHtml::encode($message); ?>
</div>
<script type="text/javascript">
	

        function initialize() {
            var geocoder = new google.maps.Geocoder();
            var myOptions = {
                zoom: 10,
                scrollwheel: false,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            var map = new google.maps.Map(document.getElementById("map"), myOptions);
            var address = "";
            var r = 0;

            if(address == "") {
                address = "Chicago, IL";
            }

            if (geocoder) {
                geocoder.geocode({ 'address': address }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        map.setCenter(results[0].geometry.location);
                         
                        var c = {
                            center: results[0].geometry.location,
                            radius: r,
                            fillColor: "#ee0000",
                            fillOpacity: 0.4,
                            strokeColor: "#ff0000",
                            strokeOpacity: 0.5
                        };

                        var cl = new google.maps.Circle(c);
                        cl.setMap(map);

                        if( document.getElementById("ctl00_ContentPlaceHolder1_cMaps").checked == true)
                        {
                            var d = {
                                center: results[0].geometry.location,
                                radius: 24000,
                                fillColor: "#00ee00",
                                fillOpacity: 0.4,
                                strokeColor: "#00ff00",
                                strokeOpacity: 0.5
                            };

                            var dl = new google.maps.Circle(d);
                            dl.setMap(map);
                        }

                        map.fitBounds(cl.getBounds());

                        marker = new google.maps.Marker({
                            position: results[0].geometry.location,
                            map: map
                        });
                        markersArray.push(marker);


                    } else { return; }
                });
            }
        }

        $(document).ready(function () { initialize(); });
    
</script>
<script type="text/javascript">
	var mapCenter = new google.maps.LatLng(referencePointLatitude, referencePointLongitude); //the ref point lat and lon must be given, usually a land mark (BLLM)
var latDiv = latDiv(mapCenter); //distance per one degree latitude in this location
var lngDiv = lngDiv(mapCenter); //distance per one degree longitude in this location
var LatLng2 = NextCoord(PrevCoord,NorthOrSouth,x,y,EastOrWest,z); //next coordinate given the bearing and distance from previous coordinate
var Lat2 = LatLng2.lat(); //next coord latitude in degrees
var Lng2 = LatLng2.lng(); //next coord longitude in degrees
var polygon=[p1,p2,...,pn-1,pn,p1]; //p1,p2,etc. are the coordinates of points of the polygon, i.e. the land Title. Be sure to close the polygon to the point of beginning p1
var area = Area(polygon); //area of the polygon in sq.m.
function NextCoord(PrevCoord,NorthOrSouth,x,y,EastOrWest,z) {
    var angle = ( x + ( y / 60 ) ) * Math.PI / 180;
    var a = 1;
    var b = 1;
    if (NorthOrSouth == 'South') { a = -1; }
    if (EastOrWest == 'West') { b = -1; }
    var nextLat = PrevCoord.lat() + ( a * z * Math.cos(angle) / latDiv );
    var nextLng = PrevCoord.lng() + ( b * z * Math.sin(angle) / lngDiv );
    var nextCoord = new google.maps.LatLng(nextLat, nextLng);
    return nextCoord;
}
function latDiv(mapCenter) {
    var p1 = new google.maps.LatLng(mapCenter.lat()-0.5, mapCenter.lng());
    var p2 = new google.maps.LatLng(mapCenter.lat()+0.5, mapCenter.lng());
    return dist(p1,p2);
}
function lngDiv(mapCenter) {
    var p3 = new google.maps.LatLng(mapCenter.lat(), mapCenter.lng()-0.5);
    var p4 = new google.maps.LatLng(mapCenter.lat(), mapCenter.lng()+0.5);
    return dist(p3,p4);
}
function dist(pt1, pt2) {
    var dLat = ( pt2.lat() - pt1.lat() ) * Math.PI / 180;
    var dLng = ( pt2.lng() - pt1.lng() ) * Math.PI / 180;
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
          Math.cos(rad(pt1.lat())) * Math.cos(rad(pt2.lat())) * 
          Math.sin(dLng/2) * Math.sin(dLng/2);
    var R = 6372800; //earth's radius
    var distance = R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    return distance;
}
function Area(polygon) {
    var xPts=[];
    for (i=1; i<polygon.length; i++) { xPts[i-1] = ( polygon[i].lat() - polygon[0].lat() ) * latDiv; }
    var yPts=[];
    for (i=1; i<polygon.length; i++) { yPts[i-1] = ( polygon[i].lng() - polygon[0].lng() ) * lngDiv; }
    var area = 0;
    j = polygon.length-2;
    for (i=0; i<polygon.length-1; i++) {
       area = area + ( xPts[j] + xPts[i] ) * ( yPts[j] - yPts[i] );
       j = i;
    }
    area = Math.abs(area/2);
    return area;
}
</script>
<?php
	$origLat = 42.1365;
	$origLon = -71.7559;
	$dist = 10; // This is the maximum distance (in miles) away from $origLat, $origLon in which to search
	$query = "SELECT name, latitude, longitude, 3956 * 2 * 
	          ASIN(SQRT( POWER(SIN(($origLat - abs(latitude))*pi()/180/2),2)
	          +COS($origLat*pi()/180 )*COS(abs(latitude)*pi()/180)
	          *POWER(SIN(($origLon-longitude)*pi()/180/2),2))) 
	          as distance FROM $tableName WHERE 
	          longitude between ($origLon-$dist/abs(cos(radians($origLat))*69)) 
	          and ($origLon+$dist/abs(cos(radians($origLat))*69)) 
	          and latitude between ($origLat-($dist/69)) 
	          and ($origLat+($dist/69)) 
	          having distance < $dist ORDER BY distance limit 100;"; 
	$result = mysql_query($query) or die(mysql_error());
	while($row = mysql_fetch_assoc($result)) {
	    echo $row['name']." > ".$row['distance']."<BR>";
	}
	
	//
if(isset($_POST['submit'])) {
     if(!preg_match('/^[0-9]{5}$/', $_POST['zipcode'])) {
          echo "<strong>You did not enter a properly formatted ZIP Code.</strong> Please try again.\n";
     }
     elseif(!preg_match('/^[0-9]{1,3}$/', $_POST['distance'])) {
          echo "<strong>You did not enter a properly formatted distance.</strong> Please try again.\n";
     }
     else {
          //connect to db server; select database
          $link = mysql_connect('host_name', 'user_name', 'password') or die('Cannot connect to database server');
          mysql_select_db('database_name') or die('Cannot select database');
 
          //query for coordinates of provided ZIP Code
          if(!$rs = mysql_query("SELECT * FROM php_zip_code_distance WHERE zip_code = '$_POST[zipcode]'")) {
               echo "<strong>There was a database error attempting to retrieve your ZIP Code.</strong> Please try again.\n";
          }
          else {
               if(mysql_num_rows($rs) == 0) {
                    echo "<strong>No database match for provided ZIP Code.</strong> Please enter a new ZIP Code.\n";
               }
               else {
                    //if found, set variables
                    $row = mysql_fetch_array($rs);
                    $lat1 = $row['latitude'];
                    $lon1 = $row['longitude'];
                    $d = $_POST['distance'];
                    //earth's radius in miles
                    $r = 3959;
 
                    //compute max and min latitudes / longitudes for search square
                    $latN = rad2deg(asin(sin(deg2rad($lat1)) * cos($d / $r) + cos(deg2rad($lat1)) * sin($d / $r) * cos(deg2rad(0))));
                    $latS = rad2deg(asin(sin(deg2rad($lat1)) * cos($d / $r) + cos(deg2rad($lat1)) * sin($d / $r) * cos(deg2rad(180))));
                    $lonE = rad2deg(deg2rad($lon1) + atan2(sin(deg2rad(90)) * sin($d / $r) * cos(deg2rad($lat1)), cos($d / $r) - sin(deg2rad($lat1)) * sin(deg2rad($latN))));
                    $lonW = rad2deg(deg2rad($lon1) + atan2(sin(deg2rad(270)) * sin($d / $r) * cos(deg2rad($lat1)), cos($d / $r) - sin(deg2rad($lat1)) * sin(deg2rad($latN))));
 
                    //display information about starting point
                    //provide max and min latitudes / longitudes
                    echo "<table class="\"bordered\"" cellspacing="\"0\"">\n";
                    echo "<tbody><tr><th>City</th><th>State</th><th>Lat</th><th>Lon</th><th>Max Lat (N)</th><th>Min Lat (S)</th><th>Max Lon (E)</th><th>Min Lon (W)</th></tr>\n";
                    echo "<tr><td>$row[city]</td><td>$row[state]</td><td>$lat1</td><td>$lon1</td><td>$latN</td><td>$latS</td><td>$lonE</td><td>$lonW</td></tr>\n";
                    echo "</tbody></table>\n\n";
 
                    //find all coordinates within the search square's area
                    //exclude the starting point and any empty city values
                    $query = "SELECT * FROM php_zip_code_distance WHERE (latitude <= $latN AND latitude >= $latS AND longitude <= $lonE AND longitude >= $lonW) AND (latitude != $lat1 AND longitude != $lon1) AND city != '' ORDER BY state, city, latitude, longitude";
                    if(!$rs = mysql_query($query)) {
                         echo "<strong>There was an error selecting nearby ZIP Codes from the database.</strong>\n";
                    }
                    elseif(mysql_num_rows($rs) == 0) {
                         echo "<strong>No nearby ZIP Codes located within the distance specified.</strong> Please try a different distance.\n";
                    }
                    else {
                         //output all matches to screen
                         echo "<table class="\"bordered\"" cellspacing="\"0\"">\n";
                         echo "<tbody><tr><th>City</th><th>State</th><th>ZIP Code</th><th>Latitude</th><th>Longitude</th><th>Miles, Point A To B</th></tr>\n";
                         while($row = mysql_fetch_array($rs)) {
                              echo "<tr><td>$row[city]</td><td>$row[state]</td><td>$row[zip_code]</td><td>$row[latitude]</td><td>$row[longitude]</td><td>";
                              echo acos(sin(deg2rad($lat1)) * sin(deg2rad($row['latitude'])) + cos(deg2rad($lat1)) * cos(deg2rad($row['latitude'])) * cos(deg2rad($row['longitude']) - deg2rad($lon1))) * $r;
                              echo "</td></tr>\n";
                         }
                         echo "</tbody></table>\n\n";
                    }
               }
          }
     }
}
?>